package com.micookie.v2ex.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.micookie.v2ex.R;
import com.micookie.v2ex.api.inf.IGetDataCallback;
import com.micookie.v2ex.model.TopicModel;
import com.micookie.v2ex.model.bean.Topic;
import com.micookie.v2ex.model.bean.TopicDetail;
import com.micookie.v2ex.ui.adapter.TopicDetailAdapter;
import com.micookie.v2ex.ui.base.BaseSwipeBackActivity;
import com.micookie.v2ex.ui.weight.SpacesItemDecoration;
import com.micookie.v2ex.utils.FastBlurUtil;
import com.micookie.v2ex.utils.UiUtils;

import net.opacapp.multilinecollapsingtoolbar.CollapsingToolbarLayout;

import butterknife.BindView;

public class TopicDetailActivity extends BaseSwipeBackActivity {
    public static final String KEY_TOPIC = "KEY_TOPIC";

    @BindView(R.id.header_topic_info_tv)
    TextView mHeaderTopicInfoTv;

    @BindView(R.id.reply_rv)
    RecyclerView mReplyRecycle;

    @BindView(R.id.topic_detail_srl)
    SwipeRefreshLayout mSwipeRefresh;

    @BindView(R.id.toolbar_layout)
    CollapsingToolbarLayout mToolbarLayout;

    @BindView(R.id.toolbar_detail)
    Toolbar mToolbar;

    @BindView(R.id.blur_iv)
    ImageView mBlurIv;

    Bitmap mAvatarBitmap;

    @BindView(R.id.header_avatar_sdv)
    SimpleDraweeView mAvatarSdv;

    TopicDetail mTopicDetail;

    TopicDetailAdapter mTopicDetailAdapter;


    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            initHeader();
            mTopicDetailAdapter.setTopicDetail(mTopicDetail);
            mTopicDetailAdapter.notifyDataSetChanged();

            mSwipeRefresh.setRefreshing(false);
            mSwipeRefresh.setEnabled(false);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topic_detail);
    }

    @Override
    public void initData() {
        super.initData();
        mTopicDetail = new TopicDetail();
        Topic topic = getIntent().getParcelableExtra(KEY_TOPIC);
        mTopicDetail.setTopic(topic);
    }

    @Override
    public void initView() {
        super.initView();
        mSwipeRefresh.setColorSchemeResources(
                R.color.refresh_progress_1,
                R.color.refresh_progress_2,
                R.color.refresh_progress_3
        );
        setSupportActionBar(mToolbar);
        //显示Toolbar左侧的返回按钮
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }


        //mToolbar.setTitle(mTopicDetail.getTopic().getTitle());
        //mCollapsingToolBar.setTitle(mTopicDetail.getTopic().getTitle());


    }


    @Override
    public void initListener() {
        super.initListener();

        mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                onPullDown();
            }
        });

        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TopicDetailActivity.this.finish();
            }
        });

        mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                return false;
            }
        });
    }


    private void onPullDown() {
        mSwipeRefresh.setRefreshing(true);
        refreshData();
    }

    @Override
    public void initLoad() {
        super.initLoad();

        mTopicDetailAdapter = new TopicDetailAdapter(this, mTopicDetail);
        mReplyRecycle.setLayoutManager(new LinearLayoutManager(this));
        mReplyRecycle.setItemAnimator(new DefaultItemAnimator());
        mReplyRecycle.addItemDecoration(new SpacesItemDecoration(getResources().getDimensionPixelSize(R.dimen.topic_list_item_decoration)));
        mReplyRecycle.setAdapter(mTopicDetailAdapter);

        Uri uri = Uri.parse(mTopicDetail.getTopic().getMember().getAvatar());
        mAvatarSdv.setImageURI(uri);

        mAvatarBitmap = UiUtils.returnFrescoBitmap(uri);
        Bitmap blurBitmap = FastBlurUtil.doBlur(mAvatarBitmap, 40, false);
        mBlurIv.setImageBitmap(blurBitmap);

        onPullDown();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.topic_detail_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    /**
     * 加载数据
     */
    private void refreshData() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                new TopicModel().getTopicDetail(mTopicDetail.getTopic().getUrlFirstPage(), new IGetDataCallback<TopicDetail>() {
                    @Override
                    public void onSuccess(TopicDetail data) {
                        mTopicDetail = data;
                        mHandler.sendEmptyMessage(0);
                    }

                    @Override
                    public void onFailed(String failedInfo) {

                    }
                });
            }
        }.start();
    }

    public static void startActivity(Context context, Topic topic) {
        Intent intent = new Intent(context, TopicDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable(KEY_TOPIC, topic);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    private void initHeader() {
        Topic topic = mTopicDetail.getTopic();
        mToolbarLayout.setTitle(topic.getTitle());
        //mHeaderTitleTv.setText(topic.getTitle());
        String topicInfo = topic.getMember().getUsername() + "/" +
                topic.getCreatedFormat() + "/" +
                topic.getClicks() + "次点击";
        mHeaderTopicInfoTv.setText(topicInfo);

    }

    @Override
    public void finish() {
        super.finish();
    }
}
